﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZLGCANoptimize
{
    public static class ZLGCanTool
    {
        const uint CAN_EFF_FLAG = 0x80000000U; /* EFF/SFF is set in the MSB */
        const uint CAN_RTR_FLAG = 0x40000000U; /* remote transmission request */
        const uint CAN_ERR_FLAG = 0x20000000U; /* error message frame */
        const uint CAN_ID_FLAG = 0x1FFFFFFFU; /* id */

        public static string[] GetData(List<ZCAN_Receive_Data> data)
        {
            List<string> list = new List<string>();
            string text = "";
            for (int i = 0; i < data.Count; ++i)
            {
                ZCAN_Receive_Data can = data[i];
                uint id = data[i].frame.can_id;
                string eff = ZLGCanTool.IsEFF(id) ? "扩展帧" : "标准帧";
                string rtr = ZLGCanTool.IsRTR(id) ? "远程帧" : "数据帧";

                //  text = String.Format("接收到CAN ID:0x{0:X8} {1:G} {2:G} 长度:{3:D1} 数据:", ZLGCanTool.GetId(id), eff, rtr, can.frame.can_dlc);
                text = "";
                for (uint j = 0; j < can.frame.can_dlc; ++j)
                {
                    text = String.Format("{0:G}{1:X2} ", text, can.frame.data[j]);
                }
                list.Add(text);
            }

            return list.ToArray();
        }

        public static uint GetId(uint id)
        {
            return id & CAN_ID_FLAG;
        }

        public static bool IsEFF(uint id)//1:extend frame 0:standard frame
        {
            return !!Convert.ToBoolean((id & CAN_EFF_FLAG));
        }

        public static bool IsRTR(uint id)//1:remote frame 0:data frame
        {
            return !!Convert.ToBoolean((id & CAN_RTR_FLAG));
        }
    }
}
